package com.citybox.shared.exception;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ObjectUtils;

@Getter
@Setter
public class Exp extends RuntimeException {

    /**
     * 异常码
     */
    private int code;

    /**
     * 错误信息
     */
    private String message;

    /**
     * 数据
     */
    private Object data;

    /**
     * 抛出异常
     */
    private Throwable throwable;

    public Exp(ICode ICode) {
        this.code = ICode.getCode();
        this.message = ICode.getMessage();
    }

    public Exp(String message) {
        this.message = message;
    }

    public Exp(Integer code, String message) {
        this.message = message;
        this.code = code;
    }

    public Exp(String message, Object... params) {
        StringBuilder sb = new StringBuilder();
        String str = "{}";
        int count = 0;
        if (ObjectUtils.isEmpty(params)) {
            this.message = message;
            return;
        }
        for (Object param : params) {
            int index = message.indexOf(str);
            if (index == -1) {
                if (count == 0) {
                    sb.append(message);
                }
                break;
            } else {
                String s = message.substring(0, index);
                message = message.substring((index + 2));
                String valStr = null != param ? param.toString() : "";
                sb.append(s).append(valStr);
                count++;
            }
        }
        sb.append(message);
        this.message = sb.toString();
    }

    public Exp(String message, Object data) {
        this(message, data, "");
        this.data = data;
    }

    public Exp(String message, Throwable throwable, Object... params) {
        this(message, params);
        this.throwable = throwable;
        this.message = message;
    }
}
